#include <iostream>
#include <windows.h>
using namespace std;
 
int main(int argc, const char **argv)
{
    cout << "Connecting to pipe..." << endl;
 
    // Open the named pipe
    // Most of these parameters aren't very relevant for pipes.
    HANDLE pipe = CreateFile(
        L"\\\\.\\pipe\\my_pipe",
        GENERIC_READ, // only need read access
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL
    );
 
    if (pipe == INVALID_HANDLE_VALUE) {
        wcout << "Failed to connect to pipe." << endl;
        // look up error code here using GetLastError()
        system("pause");
        return 1;
    }
 
    cout << "Reading data from pipe..." << endl;
 
    // The read operation will block until there is data to read
    char buffer[128];
    DWORD numBytesRead = 0;
    BOOL result = ReadFile(
        pipe,
        buffer, // the data from the pipe will be put here
        127 * sizeof(wchar_t), // number of bytes allocated
        &numBytesRead, // this will store number of bytes actually read
        NULL // not using overlapped IO
    );
 
    if (result) {
        buffer[numBytesRead / sizeof(char)] = '\0'; // null terminate the string
        cout << "Number of bytes read: " << numBytesRead << endl;
        cout << "Message: " << buffer << endl;
    } else {
        cout << "Failed to read data from the pipe." << endl;
    }
 
    // Close our pipe handle
    CloseHandle(pipe);
 
    cout << "Done. Press any key to continue" << endl;
 
    system("pause");
    return 0;
}